import type { ItemResult } from '@/types/search';
import SearchClientWorker from '@/workers/searchClient?worker';

const get = () => `/api/wiki/SearchIndex.json`

const cacheMap = new Map()
let Result: ItemResult[] = []
let SearchWorker: Worker
/**
 * 搜索
 * @param keyword 搜索关键词
 * @returns 结果
 */
export default async function getResult(keyword: string) {
  if (!Result.length) Result = await (await fetch(get())).json()
  if (!SearchWorker) SearchWorker = new SearchClientWorker()
  const hits: ItemResult[] = []
  keyword = keyword.trim().toLowerCase()
  if (keyword === "") { /* empty */ }
  else if (cacheMap.has(keyword)) {
    hits.push(...cacheMap.get(keyword))
  }
  else {
    await new Promise<void>((resolve) => {
      SearchWorker.onmessage = (res) => {
        hits.push(...res.data)
        cacheMap.set(keyword, hits)
        resolve()
      }
      SearchWorker.postMessage([keyword, Result])
    })
  }

  return {
    results: [
      {
        hits
      }
    ]
  }
}